package com.yzf.demo.demo.Thread.lock;

import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

/**
 * Created by 于占峰 on 2020/4/4/004.
 * Semaphore  类似于限流
 */
public class SemaphoreDemo extends Thread {
    private int num;
    private Semaphore semaphore;

    public SemaphoreDemo(int num, Semaphore semaphore) {
        this.num = num;
        this.semaphore = semaphore;
    }

    @Override
    public void run() {
        try {
            semaphore.acquire();//获得一个许可
            System.out.println("第" + num + "个线程获得一个许可");
            TimeUnit.SECONDS.sleep(2);//睡眠n秒后结束释放该线程
            System.out.println("第" + num + "个线程被释放");
            semaphore.release();//释放许可
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Semaphore semaphore = new Semaphore(5);//指定最多五个线程许可
        //运行十个线程
        for (int i = 1; i <= 10; i++) {
            new SemaphoreDemo(i, semaphore).start();
        }
    }
}
